﻿Imports Microsoft.VisualBasic
Imports System.Collections.Generic

Public Class CSVStreamReader
    Inherits IO.StreamReader

    Private headerField As New List(Of String)

    Public Sub New(ByVal stream As IO.Stream, ByVal encoding As Text.Encoding)
        MyBase.New(stream, encoding)

        Me.ReadHeader()
    End Sub

    Public Sub ReadHeader()
        Dim s As String = MyBase.ReadLine()

        Me.headerField.Clear()

        For Each cell As String In s.Split(",")
            Me.headerField.Add(cell)
        Next

    End Sub

    Public Function ReadRow() As Dictionary(Of String, String)
        Dim s As String = MyBase.ReadLine()
        Dim cells() As String = s.Split(",")

        If Me.IsValid(cells) = False Then
            Throw New Exception("Invalid file format")
        End If

        Dim result As New Dictionary(Of String, String)

        For i As Integer = 0 To Me.headerField.Count - 1
            result.Add(Me.headerField(i), cells(i))
        Next

        Return result
    End Function

    Private Function IsValid(ByVal cells() As String) As Boolean
        If Me.headerField.Count <> cells.Length Then
            Return False
        Else
            Return True
        End If

    End Function

    Public ReadOnly Property Header() As List(Of String)
        Get
            Return Me.headerField
        End Get
    End Property
End Class
